import React, { useEffect } from 'react';
import {View,ImageBackground,TouchableOpacity,TextInput,StyleSheet,ScrollView,Text,Image,Modal,Alert} from 'react-native';
import '../../global';
import { useState } from 'react';
import * as ImagePicker from 'expo-image-picker';
import { useSelector } from 'react-redux';
// const { View } = require("react-native")

let imgURL= require('../../assets/image/background.jpg');

const getCurrentDay = () =>{
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    let currentdate = year + '-' + month + '-' + strDate;
    return currentdate;
}

const showAlert = (msg,fun) =>
  Alert.alert(
    "提示",
    msg,
    [
      {
        text: "确认",
        onPress: fun,
        style: "cancel",
      },
    ],
    {
      cancelable: false,
    }
  );
const Check = ({navigation}) => {
  const list=useSelector(state=>state.list)
  const [value,setValue] = useState('');
  const [image,setImage] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [message,setMessage] = useState('');
  const [check,setCheck] = useState([]);
  const [num,setNum]=useState(0);
  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      base64: true,
      quality: 0.1
    });
    if (!result.cancelled) {
      fetch("https://wx.qasdwer.top:8080/pic",{
        method: 'post',
        body: JSON.stringify(result),
        headers: {
          'Content-Type': 'application/json'
        }
    
      })
      .then(res=>res.json())
      .then(res=>{

        setImage([...image,res.addr]);
        })
    }
};

    useEffect(()=>{
        fetch("https://wx.qasdwer.top:8080/home/getcheck",{
        method: 'post',
        body: JSON.stringify({account:list.account}),
        headers: {
          'Content-Type': 'application/json'
        }
    
      })
      .then(res=>res.json())
      .then(res=>{

        console.log(res)
        setCheck(res)
        setNum(res.length)
        })
    
    },[])
  return (
    <ScrollView>
        <View>
            <ImageBackground style={styles.bg} source={imgURL}>
                <View style={styles.ownmes}>
                    <Image source={{uri:list.img}} style={styles.ownimg} />
                    <View style={styles.ownname}>
                        <Text style={{color:'white'}}>{list.name}</Text>
                        <Text style={{color:'white'}}>累计打卡：{num}天</Text>
                    </View>
                </View>
            </ImageBackground>
            <View style={styles.owncon}>
                <TextInput style={styles.input} multiline={true} placeholder='这一刻我想说……' value={value} onChangeText={(text)=>{setValue(text)}}/>
                <View style={{marginTop:changeH(50),width:'100%'}}>
                    <View style={styles.bg1}>
                        <TouchableOpacity  onPress={pickImage} style={styles.button}>
                            <Text style={styles.font}>选择图片</Text>
                        </TouchableOpacity>
                        <Modal transparent={true} visible={modalVisible}>
                            <View>
                                <View style={{backgroundColor:'rgba(0,0,0,0.7)',borderRadius:20,display:'flex',justifyContent:'center',alignItems:'center',width:'70%',height:changeH(330),top:0.3*h,left:0.15*w}}>
                                    <Text style={{color:'#F5F5F5',fontSize:changeW(35),fontWeight:'bold'}}>{message}</Text>
                                </View>
                            </View>
                        </Modal>
                    </View>
                    <View style={{width:'100%',flexDirection:'row',flexWrap:'wrap'}}>
                        {
                        image && image.map((item,index)=>{
                            return(
                                <Image key={index} source={{uri: item}} style={{width:'30%',height:changeH(300),marginLeft:changeW(20),marginTop:changeH(30)}} />
                            ) 
                        })
                        }
                    </View>
                </View>
                <TouchableOpacity style={styles.button1} onPress={()=>{
                    if(list.isLogin==false){
                        setModalVisible(true);
                        setMessage('请先登录!')
                        setTimeout(()=>{
                            setModalVisible(false);
                        },2000)
                    }else{
                    if(value == ''){
                        setModalVisible(true);
                        setMessage('请输入打卡内容！');
                        setTimeout(()=>{
                            setModalVisible(false);
                        },2000)
                    }
                    else{
                        let time0 = getCurrentDay();
                        let obj = {
                            check_id:Date.now(),
                            check_time:time0,
                            checkuser_name:list.name,
                            checkuser_img:list.img,
                            check_topic:`打卡第${num+1}天`,
                            check_content:value,
                            check_img:image,
                            user_number:list.account
                        }
                        fetch("https://wx.qasdwer.top:8080/home/check",{
                            method: 'put',
                            body: JSON.stringify(obj),
                            headers: {
                              'Content-Type': 'application/json'
                            }
                        
                          })
     
    
                        setCheck([obj,...check]);
                        setModalVisible(true);
                        setMessage('发布成功！');
                        setTimeout(()=>{
                            setModalVisible(false);
                        },2000)
                        setImage([]);
                        setValue('');
                        setNum(num+1)
                    }}
                }}>
                    <Text style={styles.font}>打卡</Text>
                </TouchableOpacity>
            </View>
        </View>
        <View style={{width:'100%'}}>
            <View style={{width:'95%',marginLeft:changeW(20),marginTop:changeH(20)}}>
                <Text style={{fontSize:changeW(30),color:'#CCBE97'}}>打卡榜</Text>
            </View>
            {/* <View style={{width:'100%'}}> */}
            {/* <Text>133</Text> */}
            {
                check.map((item,index)=>{
                    return(
                    <View key={item.check_id} style={styles.checkcon1}>
                        <Image style={styles.checkimg} source={{uri:item.checkuser_img}} />
                        <View style={styles.checkcon2}>
                            <Text>{item.checkuser_name}</Text>
                            <View style={{flexDirection:'column',justifyContent:'center'}}>
                                <Text style={{color:'#CCBE97'}}>#{item.check_topic}</Text>
                                <Text>{item.check_content}</Text>
                            </View>
                            <View style={{width:'100%',flexDirection:'row',flexWrap:'wrap'}}>
                            {
                                item.check_img && item.check_img.map((item,index)=>{
                                return(
                                    <Image key={index} source={{uri: item}} style={{width:'25%',height:changeH(180),marginLeft:changeW(20),marginTop:changeH(30)}} />
                                ) 
                                })
                            }
                    </View>
                            <View style={styles.checkcon3}>
                                <Text style={{color:'#7c7c7c'}}>{item.check_time}</Text>
                            </View>
                        </View>
                    </View>
                    )
                })
            }
            {/* </View> */}
        </View>
    </ScrollView>
  )
        
}

const styles=StyleSheet.create({
    bg:{
        width:'100%',
        height:changeH(450),
    },
    ownimg:{
        width:changeW(120),
        height:changeW(120),
        borderRadius:changeW(60)
    },
    ownmes:{
        flexDirection:'row',
        marginLeft:changeW(60),
        marginTop:changeH(60)
    },
    ownname:{
        flexDirection:'column',
        justifyContent:'space-around',
        marginLeft:changeW(30)
    },
    owncon:{
        width:'95%',
        marginLeft:changeW(20),
        borderRadius:changeW(20),
        marginTop:-changeH(200),
        backgroundColor:'white',
        borderRadius:changeW(30)
    },
    input:{
        width:'100%',
        height:changeH(200),
        backgroundColor:'white',
        paddingLeft:changeW(20),
        paddingBottom:changeH(120),
        borderRadius:changeW(20)
    },
    button:{
        width:'80%',
        height:changeH(70),
        backgroundColor:'#CCBE97',
        display:'flex',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:changeW(30)
    },
    button1:{
        width:'80%',
        height:changeH(70),
        backgroundColor:'#CCBE97',
        display:'flex',
        alignItems:'center',
        justifyContent:'center',
        marginLeft:changeW(70),
        marginTop:changeH(50),
        borderRadius:changeW(30),
        marginBottom:changeH(20)
    },
    bg1:{
        display:'flex',
        alignItems:'center',
        justifyContent:'center'
    },
    font:{
        fontSize:changeW(25),
        fontWeight:'bold',
        color:'white'
    },
    checkcon1:{
        width:'95%',
        height:changeH(410),
        backgroundColor:'white',
        marginLeft:changeW(20),
        marginTop:changeH(20),
        flexDirection:'row',
        borderRadius:changeW(30)
    },
    checkcon2:{
        width:'80%',
        height:'100%',
        marginLeft:changeW(30),
        flexDirection:'column',
        justifyContent:'space-around'
    },
    checkcon3:{
        flexDirection:'row',
        justifyContent:'space-between',
        marginLeft:changeW(410)
    },
    checkimg:{
        width:changeW(60),
        height:changeW(60),
        marginTop:changeH(20),
        marginLeft:changeW(20),
        borderRadius:changeW(30)
    }
})

export default Check